package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.enums.WxMsgTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WxChatMsgFactory implements InitializingBean {

    @Resource
    List<WxChatMsgHandler> wxChatMsgHandlerList;

    // 让枚举类型和相应的handler一一对应
    Map<WxMsgTypeEnum, WxChatMsgHandler> wxChatMsgHandlerMap = new HashMap<>();

    /**
     * 通过msgType获取handler
     * @param msgType
     * @return
     */
    public WxChatMsgHandler getHandlerByMsgType(String msgType) {
        WxMsgTypeEnum wxMsgTypeEnum = WxMsgTypeEnum.getEnumByMsgType(msgType);
        if (wxMsgTypeEnum != null) {
            return wxChatMsgHandlerMap.get(wxMsgTypeEnum);
        }
        return null;
    }

    //给map写入值，重写InitializingBean接口的一个方法，bean加载完成时执行
    @Override
    public void afterPropertiesSet() throws Exception {
        for (WxChatMsgHandler wxChatMsgHandler : wxChatMsgHandlerList) {
            wxChatMsgHandlerMap.put(wxChatMsgHandler.getMsgTypeEnum(), wxChatMsgHandler);
        }

    }






}
